package com.teng.mrliuproject.ui.vmodel

import androidx.databinding.ObservableField
import com.teng.mylibrary.base.BaseViewModel
import com.teng.mylibrary.callback.livedata.event.EventLiveData
import android.graphics.Bitmap
import android.graphics.Color

import com.google.zxing.WriterException

import com.google.zxing.BarcodeFormat

import com.google.zxing.common.BitMatrix

import com.google.zxing.EncodeHintType

import com.google.zxing.qrcode.QRCodeWriter
import com.teng.mylibrary.util.SPUtil


/**
 * Description:
 * Author:       liuteng
 * CreateDate:   2022/8/17 16:57
 * UpdateRemark: 更新说明
 */
class UpdateVModel : BaseViewModel() {

    var versionName = ObservableField<String>("")
    val myUc by lazy { UIChangeObservable() }

    inner class UIChangeObservable {
        val checkUpdate: EventLiveData<Void> = EventLiveData()
        val showQrCodeNotify: EventLiveData<Bitmap> = EventLiveData()
    }

    override fun initData() {
        super.initData()
    }

    fun checkUpdate() {
        myUc.checkUpdate.call()
    }

    fun zxing(content: String) {
        val qrCodeWriter = QRCodeWriter()
        val hints: MutableMap<EncodeHintType, String?> = HashMap()
        hints[EncodeHintType.CHARACTER_SET] = "utf-8" //记得要自定义长宽
        var encode: BitMatrix? = null
        val width = 500
        val height = 500
        try {
            encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints)
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        val colors = IntArray(width * height)
        //利用for循环将要表示的信息写出来
        for (i in 0 until width) {
            for (j in 0 until height) {
                if (encode!![i, j]) {
                    colors[i * width + j] = Color.BLACK
                } else {
                    colors[i * width + j] = Color.WHITE
                }
            }
        }
        val bit = Bitmap.createBitmap(colors, width, height, Bitmap.Config.RGB_565)
        myUc.showQrCodeNotify.value = bit
    }

}